import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
///************************
/// @auther nb
/// @function 保留小数后两位
/// @创建日期 2019/9/29 9:48
///************************

class UsNumberTextInputFormatter extends TextInputFormatter {
  static const defaultDouble = 0.001;

  static double strToFloat(String str, [double defaultValue = defaultDouble]) {
    try {
      return double.parse(str);
    } catch (e) {
      return defaultValue;
    }
  }

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    if (value == ".") {
      value = "0.";
      selectionIndex++;
    } else if (value != "" &&
        value != defaultDouble.toString() &&
        strToFloat(value, defaultDouble) == defaultDouble) {
      value = oldValue.text;
      selectionIndex = oldValue.selection.end;
    }

    if (value.contains(".")) {
      ///保留小数后两位
      String s = value.substring(value.indexOf("."), value.length);
      if (s.length > 3) {
        value = value.substring(0, value.length - 1);
        selectionIndex = oldValue.selection.end;
      }
    }

    return new TextEditingValue(
      text: value,
      selection: new TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
